var express = require('express');
var router = express.Router();
var mongoose = require("../../mongoose")

//创建产品Schema
var schema = new mongoose.Schema({
    id: { type: String, require: true },//图片id
    url: { type: String, require: true },//图片地址
});
// 定义MongoDB数据模型 (表>=集合)
var Swiper = mongoose.model("swiperlists", schema);
//导入连个内置模块
var path = require('path')
var fs = require('fs')

var multer = require("multer");
var upload = multer({
    dest: 'img_Sweiper/'
}) //文件目录
//随机名
var random = require("../../utils/randomUser")
// 上传到文件地址
router.post('/uploads', upload.single('files'), async function (req, res, next) {
    //重新命名，避免重复
    let imgUrl = req.file.originalname
    let oldPath = req.file.path;
    let newPath = 'img_Sweiper/' + imgUrl;
    await fs.renameSync(oldPath, newPath)
    let CObj = {
        code: 200,
        msg: "上传成功",
        success: true,
        imgUrl: '/' + imgUrl
    }
    res.send(CObj)
});

// 上传轮播图 到数据库
router.post('/create', async function (req, res, next) {
    let body = {
        url: req.body.url,
        id: random('id-swiper-', 5)
    }
    Swiper.create(body).then((data) => {
        res.send({
            code: 200,
            success: true,
            msg: "上传成功",
            data
        })
    }).catch((err) => {
        res.send({
            code: 500,
            success: false,
            msg: "上传失败"
        })
    });

})

//查询列表信息
router.get('/list', async function (req, res, next) {
    await Swiper.find({}).then((data) => {
        res.send({
            code: 200,
            success: true,
            msg: "列表查询成功",
            data,
        })
    }).catch((err) => {
        res.send({
            code: 500,
            success: false,
            msg: "列表查询失败",
            data: err
        })
    });

})


//删除轮播图
router.post('/deleteSwiper', async function (req, res, next) {
    await Swiper.deleteOne({
        id: req.body.id
    }).then(data => {
        fs.unlinkSync('./img_Sweiper/' + req.body.url)
        res.send({
            code: 200,
            msg: "已删除",
            success: true,
            data,
        })
    }).catch((err) => {
        res.send({
            code: 500,
            success: false,
            msg: "删除失败",
            data: err
        })
    });
})
module.exports = router;